package com.tannm.doan.taskmanager.dataview;

import java.util.*;

import com.tannm.doan.taskmanager.Prefs;
import com.tannm.doan.taskmanager.Utils;
import com.tannm.doan.taskmanager.agenda.AgendaView;
import com.tannm.doan.taskmanager.database.DataRowTask;
import com.tannm.doan.taskmanager.database.Database;

import android.database.Cursor;

public class DataViewTask extends DataView {
	// Comparator type
	public class RowsComparator implements Comparator<DataViewItem> {
		public int compare(DataViewItem item1, DataViewItem item2) {
			long iPriority1 = item1.lPriority;
			long iPriority2 = item2.lPriority;

			if (iPriority1 > iPriority2)
				return 1;
			if (iPriority1 < iPriority2)
				return -1;

			if (iPriority1 == iPriority2) {
				String s1 = item1.sSubject;
				String s2 = item2.sSubject;
				return s1.compareTo(s2);
			}

			return 0;
		}
	};

	// fields
	private Calendar calDueDateCmp = Calendar.getInstance();
	private RowsComparator fnCmp = null;

	// methods
	public DataViewTask(Database db, Prefs prefs) {
		super(db, prefs);
		sTableName = Database.sTableNameTasks;
		fnCmp = new RowsComparator();
	}

	@Override
	public void addItem(Cursor cr) {
		DataViewItem item = new DataViewItem();

		item.lID = cr.getLong(DataRowTask.Fid.ID);
		item.sSubject = cr.getString(DataRowTask.Fid.SUBJECT);
		item.bDone = (cr.getLong(DataRowTask.Fid.DONE) == 1);
		item.lPriority = cr.getLong(DataRowTask.Fid.PRIORITY);
		item.bAlarm = (cr.getLong(DataRowTask.Fid.ALARM) == 1);

		if (!cr.isNull(DataRowTask.Fid.DUEDATE))
			item.lDueDate = cr.getLong(DataRowTask.Fid.DUEDATE);

		rows.add(item);
	}

	@Override
	public void filterDataForView(DataViewItem item,
			final Calendar calStartDate, final int agendaViewType) {
		// agenda view Today
		if (agendaViewType == AgendaView.viewMode.TODAY) {
			if (prefs.bShowAllTasks) {
				item.viewMode = agendaViewType;
			} else {
				if (item.useDueDate()) {
					calDueDateCmp.setTimeInMillis(item.lDueDate);
					if (Utils.yearDaysEqual(calStartDate, calDueDateCmp))
						item.viewMode = agendaViewType;
				} else {
					item.viewMode = agendaViewType;
				}
			}
		}

		// view for alarm
		if (agendaViewType == AgendaView.viewMode.TODAY_ALARM) {
			if (!item.bDone) {
				if (item.useDueDate()) {
					calDueDateCmp.setTimeInMillis(item.lDueDate);
					if (Utils.yearDaysGreater(calStartDate, calDueDateCmp))
						item.viewMode = agendaViewType;
				} else {
					item.viewMode = agendaViewType;
				}
			}
		}

	}

	@Override
	protected void filterDataPrepare(final Calendar calStartDate,
			final int agendaViewType) {

	}

	@Override
	public void sortView() {
		Collections.sort(rows, fnCmp);
	}

}
